import React, { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'

interface Danmu {
  id: number
  text?: string
  color: string
  top: number
  left: number
  speed: number
  imageUrl?: string // 表情包/图片弹幕
  width?: number
  height?: number
  isPaused: boolean
  opacity?: number // Add opacity property
}

function Sp() {
  const { t } = useTranslation();
  const [danmus, setDanmus] = useState<Danmu[]>([])
  const [inputText, setInputText] = useState('')
  const [isVisible, setIsVisible] = useState(true)
  const [currentVideo, setCurrentVideo] = useState<'数字人视频' | '瑶瑶视频'>('数字人视频')
  // Add persistedDanmus state for localStorage storage
  const [persistedDanmus, setPersistedDanmus] = useState<Danmu[]>([])
  const videoRef = useRef<HTMLVideoElement>(null)
  const danmuIdRef = useRef(0)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // Add DANMU_STORAGE_KEY constant
  const DANMU_STORAGE_KEY = 'danmu_list';

  // 常用表情
  const emojis = ['😀','😂','😎','😍','🥰','😘','😜','🤩','😭','😡','😱','👍','👎','👏','🙏','💪','🔥','💯','✨','🎉']

  // 预置表情包（使用开源 Twemoji 链接）
  const stickerUrls: string[] = [
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f600.png', // grinning
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f602.png', // joy
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f60d.png', // heart eyes
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f525.png', // fire
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f389.png', // party popper
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f973.png', // partying face
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f62d.png', // loudly crying
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f621.png', // angry
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f44d.png', // thumbs up
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f44e.png', // thumbs down
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f64f.png', // pray
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/2728.png',   // sparkle
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f4af.png', // 100
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f60e.png', // sunglasses
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f44f.png', // clap
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f4a5.png', // collision
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f631.png', // scream
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f60a.png', // smiling
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f618.png', // kiss
    'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f643.png', // upside-down
  ]

  const [showAllStickers, setShowAllStickers] = useState(false)

  // 脏话过滤：将不当词语替换为“*”
  // 说明：此列表为示例，可根据需要扩充或改进（如引入更完善词库）。
  const PROFANITY_PATTERNS: RegExp[] = [
    /\bfuck\b/gi,
    /\bsh(?:i|\*)t\b/gi,
    /\bbitch(?:es)?\b/gi,
    /\basshole\b/gi,
    /\bbastard\b/gi,
    /\bdick\b/gi,
    /\bpussy\b/gi,
    /\bsb\b/gi,
    /傻逼/gi,
    /操你妈/gi,
    /操你/gi,
    /草你/gi,
    /干你/gi,
    /你妈死了/gi,
    /狗屁/gi,
    /妈的/gi
  ]

  const sanitizeText = (text: string) => {
    let sanitized = text
    for (const re of PROFANITY_PATTERNS) {
      // 按命中词的真实长度替换为等量“*”
      sanitized = sanitized.replace(re, (match) => '*'.repeat(Array.from(match).length))
    }
    return sanitized
  }

  // 视频源配置
  const videoSources = {
    '数字人视频': '/数字人视频.mp4',
    '瑶瑶视频': '/瑶瑶.MP4'
  }

  // 切换视频
  const switchVideo = (videoType: '数字人视频' | '瑶瑶视频') => {
    setCurrentVideo(videoType)
    // 清空当前弹幕
    setDanmus([])
    // 重新加载视频
    if (videoRef.current) {
      videoRef.current.load()
    }
  }

  // 生成随机颜色
  const getRandomColor = () => {
    const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd']
    return colors[Math.floor(Math.random() * colors.length)]
  }


// - 伪随机数生成 (Pseudo-random Number Generation): 使用 Math.random() 实现位置和速度的随机化
// - 碰撞避免策略 (Collision Avoidance Strategy): 通过随机Y轴分布减少弹幕重叠
// - 性能优化 : 使用 useRef 避免ID生成时的重渲染


  // 发送弹幕
  const sendDanmu = () => {
    if (inputText.trim() === '') return

    const sanitized = sanitizeText(inputText)

    const newDanmu: Danmu = {
      id: danmuIdRef.current++,
      text: sanitized,
      color: getRandomColor(),
      top: Math.random() * 200 + 20, // 随机高度位置
      left: currentVideo === '瑶瑶视频' ? 550 : 550, // 根据视频宽度调整起始位置
      speed: Math.random() * 2 + 1, // 随机速度
      isPaused: false,
      opacity: 1 // Default opacity
    }

    setDanmus(prev => [...prev, newDanmu])
    // Update persistedDanmus when sending text danmu
    setPersistedDanmus(prev => [...prev, newDanmu])
    setInputText('')
  }

  // 发送表情（作为文字弹幕直接发送）
  const sendEmoji = (emoji: string) => {
    const newDanmu: Danmu = {
      id: danmuIdRef.current++,
      text: emoji,
      color: '#ffffff',
      top: Math.random() * 200 + 20,
      left: currentVideo === '瑶瑶视频' ? 550 : 550, // 根据视频宽度调整起始位置
      speed: Math.random() * 2 + 1,
      isPaused: false,
      opacity: 1 // Default opacity
    }
    setDanmus(prev => [...prev, newDanmu])
  }

  // 发送表情包（图片弹幕）
  const onPickSticker = () => fileInputRef.current?.click()

  const onStickerSelected: React.ChangeEventHandler<HTMLInputElement> = (e) => {
    const file = e.target.files?.[0]
    if (!file) return
    const url = URL.createObjectURL(file)
    const height = 64
    const newDanmu: Danmu = {
      id: danmuIdRef.current++,
      color: '#ffffff',
      top: Math.random() * 180 + 20,
      left: currentVideo === '瑶瑶视频' ? 550 : 550, // 根据视频宽度调整起始位置
      speed: Math.random() * 2 + 1,
      imageUrl: url,
      width: height, // 正方形
      height,
      isPaused: false,
      opacity: 1 // Default opacity
    }
    setDanmus(prev => [...prev, newDanmu])
    // Update persistedDanmus when sending emoji danmu
    setPersistedDanmus(prev => [...prev, newDanmu])
    // Update persistedDanmus when sending sticker danmu
    setPersistedDanmus(prev => [...prev, newDanmu])
    // 重置 input 以便可连续选择同一文件
    e.target.value = ''
  }

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      sendDanmu()
    }
  }

  const pauseDanmu = (id: number) => {
    setDanmus(prev => prev.map(d => d.id === id ? { ...d, isPaused: true } : d))
  }

  const resumeDanmu = (id: number) => {
    setDanmus(prev => prev.map(d => d.id === id ? { ...d, isPaused: false } : d))
  }

  // 动画弹幕
  useEffect(() => {
    const interval = setInterval(() => {
      setDanmus(prev => {
        const moved = prev.map(danmu => ({
          ...danmu,
          left: danmu.isPaused ? danmu.left : danmu.left - danmu.speed
        }))
        // 过滤移出屏幕的弹幕，并回收表情包URL资源
        const kept: Danmu[] = []
        for (const d of moved) {
          const threshold = d.imageUrl ? -150 : -100
          if (d.left > threshold) {
            kept.push(d)
          } else {
            
            if (d.imageUrl && d.imageUrl.startsWith('blob:')) {
              URL.revokeObjectURL(d.imageUrl)
            }
          }
        }
        return kept
      })
    }, 16) // 60fps

    return () => clearInterval(interval)
  }, [])

  // Add useEffect for loading danmus from localStorage on mount
  useEffect(() => {
    const storedDanmus = localStorage.getItem(DANMU_STORAGE_KEY);
    if (storedDanmus) {
      try {
        const loadedDanmus: Danmu[] = JSON.parse(storedDanmus);
        setDanmus(loadedDanmus);
        setPersistedDanmus(loadedDanmus);
        if (loadedDanmus.length > 0) {
          danmuIdRef.current = Math.max(...loadedDanmus.map(d => d.id)) + 1;
        }
      } catch (error) {
        console.error("Failed to parse danmus from localStorage", error);
        localStorage.removeItem(DANMU_STORAGE_KEY);
      }
    }
  }, []); // Empty dependency array to run only once on mount

  // Add useEffect for saving danmus to localStorage whenever danmus state changes or on page unload
  useEffect(() => {
    // This will save whenever persistedDanmus changes
    localStorage.setItem(DANMU_STORAGE_KEY, JSON.stringify(persistedDanmus));

    // Also handle beforeunload for robustness
    const handleBeforeUnload = () => {
      localStorage.setItem(DANMU_STORAGE_KEY, JSON.stringify(persistedDanmus));
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [persistedDanmus]); // Dependency on persistedDanmus to get the latest state for saving

  return (
    <div style={{ 
      position: 'relative',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      gap: '10px'
    }}>
      <style>
        {`
          .yaoyao-video {
            width: 550px !important;
            height: 350px !important;
            max-width: 550px !important;
            max-height: 350px !important;
            min-width: 550px !important;
            min-height: 350px !important;
            object-fit: contain !important;
            object-position: center !important;
          }
        `}
      </style>
      {/* 视频容器 */}
      <div style={{ position: 'relative', display: 'inline-block' }}>
        <video
          key={currentVideo} // 强制重新渲染
          ref={videoRef}
          controls
          className={currentVideo === '瑶瑶视频' ? 'yaoyao-video' : 'normal-video'}
          style={{
            borderRadius: '8px',
            boxShadow: '0 2px 10px rgba(0,0,0,0.2)',
            // 数字人视频的独立样式
            ...(currentVideo === '数字人视频' && {
              width: '550px',
              height: '350px'
            }),
            // 瑶瑶视频的独立样式
            ...(currentVideo === '瑶瑶视频' && {
              width: '550px',
              height: '350px'
            })
          }}
        >
          <source src={videoSources[currentVideo]} type="video/mp4" />
          您的浏览器不支持视频播放。
        </video>

        {/* 弹幕层 */}
        {isVisible && (
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            pointerEvents: 'none',
            overflow: 'hidden',
            borderRadius: '8px'
          }}>
            {danmus.map(danmu => (
              <div
                key={danmu.id}
                onMouseEnter={() => pauseDanmu(danmu.id)}
                onMouseLeave={() => resumeDanmu(danmu.id)}
                style={{
                  position: 'absolute',
                  top: `${danmu.top}px`,
                  left: `${danmu.left}px`,
                  zIndex: 10,
                  display: 'flex',
                  alignItems: 'center',
                  pointerEvents: 'auto',
                  opacity: danmu.opacity || 1 // Apply opacity
                }}
              >
                {danmu.imageUrl ? (
                  <img
                    src={danmu.imageUrl}
                    alt="sticker"
                    style={{
                      width: `${danmu.width || 64}px`,
                      height: `${danmu.height || 64}px`,
                      objectFit: 'contain',
                      filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.6))'
                    }}
                  />
                ) : (
                  <span
                    style={{
                      color: danmu.color,
                      fontSize: '16px',
                      fontWeight: 'bold',
                      textShadow: '1px 1px 2px rgba(0,0,0,0.8)',
                      whiteSpace: 'nowrap'
                    }}
                  >
                    {danmu.text}
                  </span>
                )}
              </div>
            ))}
          </div>
        )}

        {/* 弹幕输入框和表情/表情包 - 放在视频控件右边 */}
        <div style={{
          position: 'absolute',
          bottom: '35px',
          left: currentVideo === '瑶瑶视频' ? '200px' : '200px', // 瑶瑶视频时调整位置
          display: 'flex',
          gap: '6px',
          alignItems: 'center',
          zIndex: 20,
          pointerEvents: 'auto'
        }}>
          <input
            type="text"
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder={t('sp.input.placeholder')}
            style={{
              padding: '4px 8px',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              borderRadius: '12px',
              outline: 'none',
              fontSize: '10px',
              width: '100px',
              color: '#ffffff',
              backgroundColor: 'rgba(0, 0, 0, 0.6)',
              backdropFilter: 'blur(5px)'
            }}
          />
          <button
            onClick={sendDanmu}
            style={{
              padding: '4px 8px',
              backgroundColor: 'rgba(0, 123, 255, 0.8)',
              color: 'white',
              border: 'none',
              borderRadius: '12px',
              cursor: 'pointer',
              fontSize: '10px'
            }}
          >
            {t('sp.actions.send')}
          </button>
          {/* 切换展开/收起 预置表情包面板 */}
          <button
            onClick={() => setShowAllStickers(!showAllStickers)}
            style={{
              padding: '4px 8px',
              backgroundColor: showAllStickers ? 'rgba(108, 117, 125, 0.9)' : 'rgba(40, 167, 69, 0.9)',
              color: 'white',
              border: 'none',
              borderRadius: '12px',
              cursor: 'pointer',
              fontSize: '10px'
            }}
          >
            {showAllStickers ? t('sp.stickers.collapse') : t('sp.stickers.expand')}
          </button>
          <button
            onClick={onPickSticker}
            style={{
              padding: '4px 8px',
              backgroundColor: 'rgba(255, 193, 7, 0.9)',
              color: '#000',
              border: 'none',
              borderRadius: '12px',
              cursor: 'pointer',
              fontSize: '10px'
            }}
          >
            {t('sp.stickers.upload')}
          </button>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={onStickerSelected}
            style={{ display: 'none' }}
          />
          <button
            onClick={() => setIsVisible(!isVisible)}
            style={{
              padding: '4px 8px',
              backgroundColor: isVisible ? 'rgba(220, 53, 69, 0.8)' : 'rgba(40, 167, 69, 0.8)',
              color: 'white',
              border: 'none',
              borderRadius: '12px',
              cursor: 'pointer',
              fontSize: '10px'
            }}
          >
            {isVisible ? t('sp.actions.hide') : t('sp.actions.show')}
          </button>
        </div>

        {/* 预置表情包面板（点击表情包展开，再次点击收起） */}
        {showAllStickers && (
          <div style={{
            position: 'absolute',
            bottom: '50px',
            left: '0',
            width: '550px',
            display: 'grid',
            gridTemplateColumns: 'repeat(8, 1fr)',
            gap: '6px',
            background: 'rgba(0,0,0,0.6)',
            padding: '8px',
            borderRadius: '8px',
            pointerEvents: 'auto',
            maxHeight: '220px',
            overflowY: 'auto'
          }}>
            {/* 常用表情（emoji） */}
            {emojis.map((e) => (
              <button
                key={e}
                onClick={() => { sendEmoji(e); setShowAllStickers(false) }}
                style={{
                  padding: '6px 8px',
                  fontSize: '16px',
                  borderRadius: '6px',
                  border: 'none',
                  cursor: 'pointer',
                  background: 'rgba(255,255,255,0.85)'
                }}
              >
                {e}
              </button>
            ))}

            {stickerUrls.map((url) => (
              <button
                key={url}
                onClick={() => {
                  const height = 64
                  const newDanmu: Danmu = {
                    id: danmuIdRef.current++,
                    color: '#ffffff',
                    top: Math.random() * 180 + 20,
                    left: currentVideo === '瑶瑶视频' ? 550 : 550, // 根据视频宽度调整起始位置
                    speed: Math.random() * 2 + 1,
                    imageUrl: url,
                    width: height,
                    height,
                    isPaused: false
                  }
                  setDanmus(prev => [...prev, newDanmu])
                  setShowAllStickers(false)
                }}
                style={{
                  background: 'transparent',
                  border: 'none',
                  padding: 0,
                  cursor: 'pointer'
                }}
              >
                <img
                  src={url}
                  alt="sticker"
                  style={{ width: '100%', height: '100%', objectFit: 'contain' }}
                />
              </button>
            ))}
          </div>
        )}

        {/* 常用表情挪入预置表情包面板，收起时不显示 */}

        {/* 收起时不显示任何表情包预览 */}
      </div>

      {/* 视频切换按钮 - 定位在视频盒子上方 */}
      <div style={{
        position: 'absolute',
        top: '-60px', // 定位到视频盒子上方
        left: '50%',
        transform: 'translateX(-50%)', // 水平居中
        display: 'flex',
        flexDirection: 'row', // 水平排列
        gap: '10px',
        zIndex: 30
      }}>
        <button
          onClick={() => switchVideo('数字人视频')}
          style={{
            padding: '8px 16px',
            backgroundColor: currentVideo === '数字人视频' ? '#007bff' : '#6c757d',
            color: 'white',
            border: 'none',
            borderRadius: '6px',
            cursor: 'pointer',
            fontSize: '14px',
            fontWeight: 'bold',
            transition: 'background-color 0.3s',
            whiteSpace: 'nowrap'
          }}
        >
          {t('sp.video1')}
        </button>
        <button
          onClick={() => switchVideo('瑶瑶视频')}
          style={{
            padding: '8px 16px',
            backgroundColor: currentVideo === '瑶瑶视频' ? '#007bff' : '#6c757d',
            color: 'white',
            border: 'none',
            borderRadius: '6px',
            cursor: 'pointer',
            fontSize: '14px',
            fontWeight: 'bold',
            transition: 'background-color 0.3s',
            whiteSpace: 'nowrap'
          }}
        >
          {t('sp.video2')}
        </button>
      </div>
    </div>
  )
}

export default Sp

